<template>
  <div class="wizard-container">
    <!-- 步骤指示器 -->
    <div style="text-align: center; margin-bottom: 10px; color: #909399; font-size: 12px;">
      步骤 {{ currentStep + 1 }} / 3
    </div>
    
    <el-steps :active="currentStep" finish-status="success" align-center>
      <el-step title="选择数据源" />
      <el-step title="配置映射关系" />
      <el-step title="确认配置" />
    </el-steps>

    <div class="step-content">
      <!-- 步骤1：选择数据源 -->
      <div v-if="currentStep === 0" class="database-selection">
        <el-row :gutter="30">
          <!-- 源数据库配置 -->
          <el-col :span="12">
            <el-card class="source-db">
              <template #header>
                <div class="card-header">
                  <h3>源数据配置</h3>
                </div>
              </template>
              <el-form :model="sourceConfig" label-width="100px">
                <el-form-item label="数据中心">
                  <el-select 
                    v-model="sourceConfig.dataCenter" 
                    placeholder="请选择数据中心"
                    style="width: 100%"
                    @change="handleSourceDataCenterChange"
                  >
                    <el-option
                      v-for="item in dataCenterOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="数据库实例">
                  <el-select 
                    v-model="sourceConfig.instance" 
                    placeholder="请选择数据库实例"
                    style="width: 100%"
                    :disabled="!sourceConfig.dataCenter"
                    @change="handleSourceInstanceChange"
                  >
                    <el-option
                      v-for="item in sourceInstanceOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="选择数据库">
                  <el-select
                    v-model="sourceConfig.databases"
                    multiple
                    filterable
                    placeholder="请选择数据库"
                    style="width: 100%"
                    :disabled="!sourceConfig.instance"
                    @change="handleSourceDatabaseChange"
                  >
                    <el-option
                      v-for="item in sourceDatabaseOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="选择表">
                  <div class="table-filter">
                    <el-input
                      v-model="sourceTableFilter"
                      placeholder="输入关键字筛选"
                      clearable
                      style="width: 100%"
                    >
                      <template #prefix>
                        <el-icon><Search /></el-icon>
                      </template>
                    </el-input>
                  </div>
                  <div class="selected-count" v-if="selectedSourceTableCount > 0">
                    已选择 {{ selectedSourceTableCount }} 张表
                  </div>
                  <el-table
                    :data="paginatedSourceTableList"
                    @selection-change="handleSourceTableSelectionChange"
                    style="width: 100%"
                    row-key="uniqueKey"
                    ref="sourceTableRef"
                  >
                    <el-table-column type="selection" :reserve-selection="true" />
                    <el-table-column prop="database" label="数据库" />
                    <el-table-column prop="label" label="表名" />
                    <el-table-column label="正则匹配" width="100" align="center">
                      <template #default="scope">
                        <el-checkbox
                          v-model="scope.row.regex"
                          @change="handleRegexChange(scope.row)"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-pagination
                    v-if="filteredSourceTableList.length > sourceTablePageSize"
                    class="table-pagination"
                    v-model:current-page="sourceTableCurrentPage"
                    v-model:page-size="sourceTablePageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="filteredSourceTableList.length"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSourceTableSizeChange"
                    @current-change="handleSourceTableCurrentChange"
                  />
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>

          <!-- 目标数据配置 -->
          <el-col :span="12">
            <el-card class="target-db">
              <template #header>
                <div class="card-header">
                  <h3>目标数据配置</h3>
                </div>
              </template>
              <el-form :model="targetConfig" label-width="100px">
                <el-form-item label="数据中心">
                  <el-select 
                    v-model="targetConfig.dataCenter" 
                    placeholder="请选择数据中心"
                    style="width: 100%"
                    @change="handleTargetDataCenterChange"
                  >
                    <el-option
                      v-for="item in dataCenterOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="数据库实例">
                  <el-select 
                    v-model="targetConfig.instance" 
                    placeholder="请选择数据库实例"
                    style="width: 100%"
                    :disabled="!targetConfig.dataCenter"
                    @change="handleTargetInstanceChange"
                  >
                    <el-option
                      v-for="item in targetInstanceOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="选择数据库">
                  <el-select
                    v-model="targetConfig.databases"
                    multiple
                    filterable
                    placeholder="请选择数据库"
                    style="width: 100%"
                    :disabled="!targetConfig.instance"
                    @change="handleTargetDatabaseChange"
                  >
                    <el-option
                      v-for="item in targetDatabaseOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="选择表">
                  <div class="table-filter">
                    <el-input
                      v-model="targetTableFilter"
                      placeholder="输入关键字筛选"
                      clearable
                      style="width: 100%"
                    >
                      <template #prefix>
                        <el-icon><Search /></el-icon>
                      </template>
                    </el-input>
                  </div>
                  <div class="selected-count" v-if="selectedTargetTableCount > 0">
                    已选择 {{ selectedTargetTableCount }} 张表
                  </div>
                  <el-table
                    :data="paginatedTargetTableList"
                    style="width: 100%"
                    row-key="uniqueKey"
                    ref="targetTableRef"
                    @selection-change="handleTargetTableSelectionChange"
                  >
                    <el-table-column type="selection" :reserve-selection="true" width="55" />
                    <el-table-column prop="database" label="数据库" />
                    <el-table-column prop="label" label="表名" />
                  </el-table>
                  <el-pagination
                    v-if="filteredTargetTableList.length > targetTablePageSize"
                    class="table-pagination"
                    v-model:current-page="targetTableCurrentPage"
                    v-model:page-size="targetTablePageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="filteredTargetTableList.length"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleTargetTableSizeChange"
                    @current-change="handleTargetTableCurrentChange"
                  />
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 步骤2：配置映射关系 -->
      <div v-if="currentStep === 1">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>表映射配置</h3>
            </div>
          </template>
          
          <!-- 表映射搜索和过滤 -->
          <div class="table-mapping-filters">
            <el-row :gutter="24" align="middle">
              <el-col :span="8">
                <el-input
                  v-model="tableMappingFilter"
                  placeholder="搜索表映射（源表/目标表）"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </el-col>
              <el-col :span="16">
                <div class="filter-actions">
                  <el-tooltip 
                    content="根据表名自动创建映射关系，保留已有映射，只为未映射的表创建新映射" 
                    placement="top"
                  >
                    <el-button type="success" size="small" @click="smartMapping">
                      智能映射
                    </el-button>
                  </el-tooltip>
                  <el-button type="primary" size="small" @click="expandAllMappings">
                    展开全部
                  </el-button>
                  <el-button type="default" size="small" @click="collapseAllMappings">
                    收起全部
                  </el-button>
                  <span class="mapping-count">
                    共 {{ filteredTableMappings.length }} 个映射
                  </span>
                </div>
              </el-col>
            </el-row>
          </div>
          
          <!-- 表映射分页控制 -->
          <div v-if="filteredTableMappings.length > tableMappingPageSize" class="table-mapping-pagination-top">
            <el-pagination
              v-model:current-page="tableMappingCurrentPage"
              :page-size="tableMappingPageSize"
              :total="filteredTableMappings.length"
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[5, 10, 20, 50]"
              @size-change="handleTableMappingSizeChange"
              @current-change="handleTableMappingCurrentChange"
            />
          </div>
          
          <el-table
            :data="paginatedTableMappings"
            style="width: 100%"
            row-key="id"
            :expand-row-keys="Array.from(expandedRows)"
            @expand-change="handleExpandChange"
            :fit="true"
          >
            <el-table-column type="expand" width="50">
              <template #default="props">
                <div class="field-mapping-container">
                  <div class="mapping-title">
                    字段映射配置
                    <span class="field-count-info">
                      (共 {{ getFieldMappingData(props.row).total }} 个字段)
                    </span>
                    <span 
                      v-if="getUnmappedFieldsCount(props.row) > 0" 
                      class="error-info"
                    >
                      - 还有 {{ getUnmappedFieldsCount(props.row) }} 个字段未配置
                    </span>
                  </div>
                  <el-table
                    :data="getFieldMappingData(props.row).data"
                    class="field-mapping-table"
                    row-key="targetField"
                    border
                    :row-class-name="getRowClassName"
                    :fit="true"
                  >
                    <el-table-column label="源字段" min-width="200">
                      <template #default="scope">
                        <template v-if="scope.row.mappingType === 'field'">
                          <el-select
                            v-model="scope.row.sourceField"
                            placeholder="选择源字段"
                            style="width: 100%"
                            :class="{ 'matched-field': scope.row.matched }"
                            @change="() => handleSourceFieldChange(scope.row)"
                            filterable
                            clearable
                          >
                            <el-option
                              v-for="field in getSourceFieldsForMapping(props.row)"
                              :key="field.name"
                              :label="field.name"
                              :value="field.name"
                            >
                              <div class="field-option">
                                <span>{{ field.name }}</span>
                                <span class="field-type">({{ field.type }})</span>
                        </div>
                            </el-option>
                          </el-select>
                        </template>
                        <template v-else>
                          <el-input
                            v-model="scope.row.defaultValue"
                            placeholder="请输入默认值"
                            style="width: 100%"
                          />
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="映射类型" min-width="140">
                      <template #default="scope">
                        <el-select 
                          v-model="scope.row.mappingType" 
                          style="width: 100%"
                          @change="() => handleMappingTypeChange(scope.row)"
                        >
                          <el-option
                            v-for="option in mappingTypeOptions"
                            :key="option.value"
                            :label="option.label"
                            :value="option.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="目标字段" min-width="200">
                      <template #default="scope">
                        <el-select
                          v-model="scope.row.targetField"
                          placeholder="选择目标字段"
                          style="width: 100%"
                          :class="{ 'matched-field': scope.row.matched }"
                          @change="() => handleTargetFieldChange(scope.row, props.row)"
                          filterable
                          clearable
                        >
                          <el-option
                            v-for="field in getTargetFieldsForMapping(props.row)"
                            :key="field.name"
                            :label="field.name"
                            :value="field.name"
                          >
                            <div class="field-option">
                              <span>{{ field.name }}</span>
                              <span class="field-type">({{ field.type }})</span>
                            </div>
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="状态" min-width="100">
                      <template #default="scope">
                        <el-tag :type="getStatusType(scope.row)">
                          {{ getStatusText(scope.row) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80" align="center">
                      <template #default="scope">
                        <el-button
                          type="danger"
                          link
                          @click="removeFieldMapping(props.row, scope.row)"
                        >
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  
                  <!-- 字段映射分页（仅当字段数量>100时显示） -->
                  <div 
                    v-if="getFieldMappingData(props.row).needPagination" 
                    class="field-mapping-pagination"
                  >
                    <el-pagination
                      :current-page="getFieldMappingData(props.row).currentPage"
                      :page-size="fieldMappingPageSize"
                      :total="getFieldMappingData(props.row).total"
                      layout="total, prev, pager, next, jumper"
                      @current-change="(page) => handleFieldMappingPageChange(props.row, page)"
                      size="small"
                    />
                  </div>
                  
                  <!-- 添加新增字段映射按钮 -->
                  <div class="field-mapping-actions">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="addFieldMapping(props.row)"
                      :loading="loadingFieldsMap.get(props.row.id)"
                    >
                      新增字段映射
                    </el-button>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="源表" min-width="200">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.sourceTable" 
                  placeholder="选择源表" 
                  style="width: 100%" 
                  filterable
                  clearable
                  @change="(value) => handleSourceTableSelect(value, scope.row)"
                >
                  <el-option
                    v-for="table in uniqueSourceTableOptions"
                    :key="table.uniqueKey"
                    :label="`${table.database}.${table.name}`"
                    :value="`${table.database}.${table.name}`"
                  >
                    <span>{{ table.database }}.</span>
                    <span style="color: #409EFF">{{ table.name }}</span>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="目标表" min-width="200">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.targetTable" 
                  placeholder="选择目标表" 
                  style="width: 100%" 
                  filterable
                  clearable
                  @change="(value) => handleTargetTableSelect(value, scope.row)"
                >
                  <el-option
                    v-for="table in uniqueTargetTableOptions"
                    :key="table.uniqueKey"
                    :label="`${table.database}.${table.name}`"
                    :value="`${table.database}.${table.name}`"
                  >
                    <span>{{ table.database }}.</span>
                    <span style="color: #409EFF">{{ table.name }}</span>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right" align="center">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="removeTableMapping(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="table-mapping-actions">
            <el-button type="primary" @click="addTableMapping">
              添加表映射
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 步骤3：确认配置 -->
      <div v-if="currentStep === 2">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>配置确认</h3>
            </div>
          </template>
          
          <el-descriptions title="源端任务模板配置" :column="2" border>
            <el-descriptions-item label="模板类型">
              <div class="db-type-with-template">
                <span>{{ sourceConfig.dbType }}</span>
                <el-select v-model="sourceConfig.templateId" placeholder="请选择绑定模板" style="width: 350px; margin-left: 10px" @change="handleTemplateChange">
                  <el-option
                    v-for="item in templateOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="目标端任务模板配置">
              <div class="db-type-with-template">
                <span>{{ targetConfig.dbType }}</span>
                <el-select v-model="targetConfig.templateId" placeholder="请选择绑定模板" style="width: 350px; margin-left: 10px" @change="handleTemplateChange">
                  <el-option
                    v-for="item in templateOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </div>
            </el-descriptions-item>
            <el-descriptions-item v-if="hasKafkaTemplate" label="绑定主题">
              <el-input 
                v-model="kafkaTopic" 
                placeholder="请输入Kafka主题名称，非必填" 
                style="width: 350px; margin-left: 10px"
                clearable
                maxlength="100"
                show-word-limit
              />
            </el-descriptions-item>
            <el-descriptions-item v-if="hasKafkaTemplate" label="绑定消费组">
              <el-input 
                v-model="kafkaConsumerGroup" 
                placeholder="请输入kafka消费组，非必填" 
                style="width: 350px; margin-left: 10px"
                clearable
                maxlength="100"
                show-word-limit
              />
            </el-descriptions-item>
            <el-descriptions-item v-if="hasKafkaTemplate" label="并发消费数">
              <el-input 
                v-model="kafkaPartition" 
                placeholder="请输入并发消费数(如：3)，非必填" 
                style="width: 350px; margin-left: 10px"
                clearable
                type="number"
                min="1"
                max="100"
              />
            </el-descriptions-item>
          </el-descriptions>

          <h4 class="mapping-summary-title">映射关系概要</h4>
          <el-table :data="tableMappings" border style="width: 100%">
            <el-table-column type="expand">
              <template #default="props">
                <el-table :data="props.row.fieldMappings" border style="width: 100%">
                  <el-table-column label="源字段" prop="sourceField" align="center" />
                  <el-table-column label="映射类型" align="center">
                    <template #default="scope">
                      {{ scope.row.mappingType === 'field' ? '字段映射' : '默认值' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="目标字段" prop="targetField" align="center" />
                  <el-table-column label="默认值" align="center">
                    <template #default="scope">
                      {{ scope.row.mappingType === 'default' ? scope.row.defaultValue : '-' }}
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="源表" align="center">
              <template #default="scope">
                {{ getSourceTableFullName(scope.row.sourceTable) }}
              </template>
            </el-table-column>
            <el-table-column label="目标表" align="center">
              <template #default="scope">
                {{ getTargetTableFullName(scope.row.targetTable) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <!-- 导航按钮 -->
      <div class="step-buttons">
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button
          v-if="currentStep < 2"
          type="primary"
          @click="nextStep"
        >下一步</el-button>
        <el-button
          v-else
          type="primary"
          :loading="loading"
          @click="submitConfig"
        >{{ configId ? '更新配置' : '生成配置' }}</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getDataCenters, getInstances, getDatabases, getTables, getTableFields } from '@/api/datasourceQuery'
import { generateSyncConfig, validateKafkaConsumerGroup } from '@/api/sync'
import { useRouter } from 'vue-router'
import { getTemplateList } from '@/api/metadata'
import { Search } from '@element-plus/icons-vue'

// ProductId字段默认值映射常量
const PRODUCT_FIELD_MAP = new Map([
  ['_en', '3366'],
  ['_ru', '3371'],
  ['_id', '3501'],
  ['_fr', '3311'],
  ['_ft', '3333'],
  ['_pt', '3322'],
  ['_sp', '3388'],
  ['_jp', '3399'],
  ['_tw', '3333'],
  ['_and2', '7757'],
  ['_cd2', '8858'],
  ['_and', '7777'],
  ['_cd', '8888'],
  ['_th', '3511']  
])

const currentStep = ref(0)
const router = useRouter()

// 源数据库配置
const sourceConfig = reactive({
  dataCenter: '', // 数据中心
  instance: '',   // 数据库实例
  dbType: '',     // 数据库类型
  databases: [],  // 选中的数据库
  selectedTables: [], // 选中的表
  templateId: ''  // 绑定模板ID
})

// 目标数据库配置
const targetConfig = reactive({
  dataCenter: '',
  instance: '',
  dbType: '',
  databases: [],
  selectedTables: [],
  templateId: ''  // 绑定模板ID
})

// 选项数据
const dataCenterOptions = ref([])
const sourceInstanceOptions = ref([])
const sourceDatabaseOptions = ref([])
const sourceTableList = ref([])
const targetInstanceOptions = ref([])
const targetDatabaseOptions = ref([])
const targetTableOptions = ref([])

// 加载状态
const loading = ref(false)

// 添加字段信息缓存
const sourceFieldsCache = ref(new Map())
const targetFieldsCache = ref(new Map())

// 添加配置ID的响应式引用
const configId = ref('')

// 添加加载状态管理
const loadingFieldsMap = ref(new Map())

// 添加表级别的字段缓存
const tableLevelSourceFields = ref(new Map())
const tableLevelTargetFields = ref(new Map())

// 添加模板选项
const templateOptions = ref([])

// 添加Kafka相关变量
const kafkaTopic = ref('')
const kafkaPartition = ref('')
const kafkaConsumerGroup= ref('')

// 缓存配置数据用于延迟回显
const savedKafkaConfig = ref(null)

// 添加筛选关键字
const sourceTableFilter = ref('')
const targetTableFilter = ref('')

// 添加分页相关变量
const sourceTableCurrentPage = ref(1)
const sourceTablePageSize = ref(20)
const targetTableCurrentPage = ref(1)
const targetTablePageSize = ref(20)

// 添加表映射分页管理
const tableMappingCurrentPage = ref(1)
const tableMappingPageSize = ref(10)

// 添加表映射搜索和过滤
const tableMappingFilter = ref('')

// 过滤后的表映射
const filteredTableMappings = computed(() => {
  let filtered = tableMappings.value
  
  // 根据搜索关键字过滤
  if (tableMappingFilter.value) {
    const keyword = tableMappingFilter.value.toLowerCase()
    filtered = filtered.filter(mapping => 
      mapping.sourceTable.toLowerCase().includes(keyword) ||
      mapping.targetTable.toLowerCase().includes(keyword)
    )
  }
  
  return filtered
})

// 添加筛选后的表格数据
const filteredSourceTableList = computed(() => {
  if (!sourceTableFilter.value) {
    return sourceTableList.value
  }
  const keyword = sourceTableFilter.value.toLowerCase()
  return sourceTableList.value.filter(table => 
    table.database.toLowerCase().includes(keyword) || 
    table.label.toLowerCase().includes(keyword)
  )
})

const filteredTargetTableList = computed(() => {
  if (!targetTableFilter.value) {
    return targetTableOptions.value
  }
  const keyword = targetTableFilter.value.toLowerCase()
  return targetTableOptions.value.filter(table => 
    table.database.toLowerCase().includes(keyword) || 
    table.label.toLowerCase().includes(keyword)
  )
})

// 添加分页后的表格数据
const paginatedSourceTableList = computed(() => {
  const start = (sourceTableCurrentPage.value - 1) * sourceTablePageSize.value
  const end = start + sourceTablePageSize.value
  return filteredSourceTableList.value.slice(start, end)
})

const paginatedTargetTableList = computed(() => {
  const start = (targetTableCurrentPage.value - 1) * targetTablePageSize.value
  const end = start + targetTablePageSize.value
  return filteredTargetTableList.value.slice(start, end)
})

// 获取分页后的表映射
const paginatedTableMappings = computed(() => {
  if (filteredTableMappings.value.length <= tableMappingPageSize.value) {
    return filteredTableMappings.value
  }
  
  const startIndex = (tableMappingCurrentPage.value - 1) * tableMappingPageSize.value
  const endIndex = startIndex + tableMappingPageSize.value
  
  return filteredTableMappings.value.slice(startIndex, endIndex)
})

// 添加去重的源表和目标表选项（用于表映射配置）
const uniqueSourceTableOptions = computed(() => {
  const uniqueMap = new Map()
  sourceConfig.selectedTables.forEach(table => {
    const key = `${table.database}.${table.name}`
    if (!uniqueMap.has(key)) {
      uniqueMap.set(key, table)
    }
  })
  return Array.from(uniqueMap.values())
})

const uniqueTargetTableOptions = computed(() => {
  const uniqueMap = new Map()
  targetConfig.selectedTables.forEach(table => {
    const key = `${table.database}.${table.name}`
    if (!uniqueMap.has(key)) {
      uniqueMap.set(key, table)
    }
  })
  return Array.from(uniqueMap.values())
})

// 判断是否有kafka模板
const hasKafkaTemplate = computed(() => {
  if (!sourceConfig.templateId && !targetConfig.templateId) {
    return false
  }
  
  const sourceTemplate = templateOptions.value.find(template => template.id === sourceConfig.templateId)
  const targetTemplate = templateOptions.value.find(template => template.id === targetConfig.templateId)
  
  const sourceIsKafka = sourceTemplate && sourceTemplate.name.toLowerCase().includes('kafka')
  const targetIsKafka = targetTemplate && targetTemplate.name.toLowerCase().includes('kafka')
  
  return sourceIsKafka || targetIsKafka
})

// 获取数据中心列表
const fetchDataCenters = async () => {
  try {
    loading.value = true
    const centers = await getDataCenters()
    dataCenterOptions.value = centers.map(center => ({
      value: center.code,
      label: center.name,
      dbType: center.type // 添加数据库类型
    }))
  } catch (error) {
    console.error('获取数据中心列表失败：', error)
    ElMessage.error('获取数据中心列表失败')
  } finally {
    loading.value = false
  }
}

// 获取源端实例列表
const fetchSourceInstances = async () => {
  if (!sourceConfig.dataCenter) return
  try {
    loading.value = true
    const instances = await getInstances(sourceConfig.dataCenter)
    sourceInstanceOptions.value = instances.map(instance => ({
      value: instance,
      label: instance
    }))
  } catch (error) {
    console.error('获取源端实例列表失败：', error)
    ElMessage.error('获取源端实例列表失败')
  } finally {
    loading.value = false
  }
}

// 获取源端数据库列表
const fetchSourceDatabases = async () => {
  if (!sourceConfig.dataCenter || !sourceConfig.instance) return
  try {
    loading.value = true
    const databases = await getDatabases(sourceConfig.dataCenter, sourceConfig.instance)
    sourceDatabaseOptions.value = databases.map(db => ({
      value: db,
      label: db
    }))
  } catch (error) {
    console.error('获取源端数据库列表失败：', error)
    ElMessage.error('获取源端数据库列表失败')
  } finally {
    loading.value = false
  }
}

// 获取源端表列表
const fetchSourceTables = async () => {
  if (!sourceConfig.dataCenter || !sourceConfig.instance || !sourceConfig.databases.length) return
  try {
    loading.value = true
    // 获取所有选中数据库的表信息
    const allTables = []
    for (const database of sourceConfig.databases) {
      const tables = await getTables(sourceConfig.dataCenter, sourceConfig.instance, database)
      allTables.push(...tables.map(table => ({
        value: `${database}.${table}`, // 使用数据库名和表名的组合作为值
        label: table,
        database: database,
        uniqueKey: `${database}.${table}`, // 添加唯一标识
        regex: false // 添加正则匹配标志
      })))
    }
    sourceTableList.value = allTables
    
    // 【修复】获取表列表后，清理不存在的已选中表
    sourceConfig.selectedTables = sourceConfig.selectedTables.filter(selectedTable => 
      allTables.some(table => 
        table.database === selectedTable.database && table.label === selectedTable.name
      )
    )
    
    // 【修复】延迟恢复选中状态，确保DOM更新完成
    nextTick(() => {
      restoreSourceTableSelection()
    })
  } catch (error) {
    console.error('获取源端表列表失败：', error)
    ElMessage.error('获取源端表列表失败')
  } finally {
    loading.value = false
  }
}

// 获取目标端实例列表
const fetchTargetInstances = async () => {
  if (!targetConfig.dataCenter) return
  try {
    loading.value = true
    const instances = await getInstances(targetConfig.dataCenter)
    targetInstanceOptions.value = instances.map(instance => ({
      value: instance,
      label: instance
    }))
  } catch (error) {
    console.error('获取目标端实例列表失败：', error)
    ElMessage.error('获取目标端实例列表失败')
  } finally {
    loading.value = false
  }
}

// 获取目标端数据库列表
const fetchTargetDatabases = async () => {
  if (!targetConfig.dataCenter || !targetConfig.instance) return
  try {
    loading.value = true
    const databases = await getDatabases(targetConfig.dataCenter, targetConfig.instance)
    targetDatabaseOptions.value = databases.map(db => ({
      value: db,
      label: db
    }))
  } catch (error) {
    console.error('获取目标端数据库列表失败：', error)
    ElMessage.error('获取目标端数据库列表失败')
  } finally {
    loading.value = false
  }
}

// 获取目标端表列表
const fetchTargetTables = async () => {
  if (!targetConfig.dataCenter || !targetConfig.instance || !targetConfig.databases.length) return
  try {
    loading.value = true
    // 获取所有选中数据库的表信息
    const allTables = []
    for (const database of targetConfig.databases) {
      const tables = await getTables(targetConfig.dataCenter, targetConfig.instance, database)
      allTables.push(...tables.map(table => ({
        value: `${database}.${table}`, // 使用数据库名和表名的组合作为值
        label: table,
        database: database,
        uniqueKey: `${database}.${table}` // 添加唯一标识
      })))
    }
    targetTableOptions.value = allTables
    
    // 【修复】获取表列表后，清理不存在的已选中表
    targetConfig.selectedTables = targetConfig.selectedTables.filter(selectedTable => 
      allTables.some(table => 
        table.database === selectedTable.database && table.label === selectedTable.name
      )
    )
    
    // 【修复】延迟恢复选中状态，确保DOM更新完成
    nextTick(() => {
      restoreTargetTableSelection()
    })
  } catch (error) {
    console.error('获取目标端表列表失败：', error)
    ElMessage.error('获取目标端表列表失败')
  } finally {
    loading.value = false
  }
}

// 获取模板列表
const fetchTemplateList = async () => {
  try {
    const response = await getTemplateList()
    templateOptions.value = response.map(item => ({
      id: item.id,
      name: item.name
    }))
  } catch (error) {
    console.error('获取模板列表失败：', error)
    ElMessage.error('获取模板列表失败')
  }
}

// 监听数据变化
watch(sourceConfig.dataCenter, () => {
  sourceConfig.instance = ''
  sourceConfig.databases = []
  sourceConfig.selectedTables = []
  sourceFieldsCache.value.clear()
  
  // 更新数据库类型
  const selectedCenter = dataCenterOptions.value.find(center => center.value === sourceConfig.dataCenter)
  if (selectedCenter) {
    sourceConfig.dbType = selectedCenter.dbType
  }
  
  fetchSourceInstances()
})

watch(sourceConfig.instance, () => {
  sourceConfig.databases = []
  sourceConfig.selectedTables = []
  fetchSourceDatabases()
  sourceFieldsCache.value.clear()
})

watch(sourceConfig.databases, (newDatabases, oldDatabases) => {
  // 【修复】不要清空所有选中的表，而是智能处理
  if (newDatabases && newDatabases.length > 0) {
    // 过滤掉不在新数据库列表中的已选中表
    sourceConfig.selectedTables = sourceConfig.selectedTables.filter(selectedTable => 
      newDatabases.includes(selectedTable.database)
    )
  } else {
    // 如果没有选中任何数据库，则清空所有选中的表
    sourceConfig.selectedTables = []
  }
  
  fetchSourceTables()
})

watch(targetConfig.dataCenter, () => {
  targetConfig.instance = ''
  targetConfig.databases = []
  targetConfig.selectedTables = []
  targetFieldsCache.value.clear()
  
  // 更新数据库类型
  const selectedCenter = dataCenterOptions.value.find(center => center.value === targetConfig.dataCenter)
  if (selectedCenter) {
    targetConfig.dbType = selectedCenter.dbType
  }
  
  fetchTargetInstances()
})

watch(targetConfig.instance, () => {
  targetConfig.databases = []
  targetConfig.selectedTables = []
  fetchTargetDatabases()
})

watch(targetConfig.databases, (newDatabases, oldDatabases) => {
  // 【修复】不要清空所有选中的表，而是智能处理
  if (newDatabases && newDatabases.length > 0) {
    // 过滤掉不在新数据库列表中的已选中表
    targetConfig.selectedTables = targetConfig.selectedTables.filter(selectedTable => 
      newDatabases.includes(selectedTable.database)
    )
  } else {
    // 如果没有选中任何数据库，则清空所有选中的表
    targetConfig.selectedTables = []
  }
  
  fetchTargetTables()
})

// 添加对筛选条件的监听，重置分页并恢复选中状态
watch(sourceTableFilter, () => {
  sourceTableCurrentPage.value = 1
  // 筛选条件变化后也需要恢复选中状态
  nextTick(() => {
    restoreSourceTableSelection()
  })
})

watch(targetTableFilter, () => {
  targetTableCurrentPage.value = 1
  // 筛选条件变化后也需要恢复选中状态
  nextTick(() => {
    restoreTargetTableSelection()
  })
})

// 添加对分页数据变化的监听，自动恢复选中状态
watch(paginatedSourceTableList, () => {
  nextTick(() => {
    restoreSourceTableSelection()
  })
}, { flush: 'post' })

watch(paginatedTargetTableList, () => {
  nextTick(() => {
    restoreTargetTableSelection()
  })
}, { flush: 'post' })

// 监听模板变更，清空Kafka字段
watch(() => sourceConfig.templateId, () => {
  if (!hasKafkaTemplate.value) {
    kafkaTopic.value = ''
    kafkaPartition.value = ''
    kafkaConsumerGroup.value = ''
  } else if (savedKafkaConfig.value) {
    // 如果有缓存的配置，尝试回显
    kafkaTopic.value = savedKafkaConfig.value.kafkaTopic || ''
    kafkaPartition.value = savedKafkaConfig.value.kafkaPartition || ''
    kafkaConsumerGroup.value = savedKafkaConfig.value.kafkaConsumerGroup || ''
    savedKafkaConfig.value = null
  }
})

watch(() => targetConfig.templateId, () => {
  if (!hasKafkaTemplate.value) {
    kafkaTopic.value = ''
    kafkaPartition.value = ''
  } else if (savedKafkaConfig.value) {
    // 如果有缓存的配置，尝试回显
    kafkaTopic.value = savedKafkaConfig.value.kafkaTopic || ''
    kafkaPartition.value = savedKafkaConfig.value.kafkaPartition || ''
    kafkaConsumerGroup.value = savedKafkaConfig.value.kafkaConsumerGroup || ''
    savedKafkaConfig.value = null
  }
})

onMounted(() => {
  fetchDataCenters()
  fetchTemplateList()
  // 检查是否有配置数据需要回显
  const savedConfig = localStorage.getItem('syncConfigData')
  if (savedConfig) {
    try {
      const configData = JSON.parse(savedConfig)
      
      // 保存配置ID
      if (configData.id) {
        configId.value = configData.id
      }
      
      // 回显源配置
      sourceConfig.dataCenter = configData.sourceConfig.dataCenter
      sourceConfig.instance = configData.sourceConfig.instance
      sourceConfig.databases = configData.sourceConfig.databases
      sourceConfig.selectedTables = configData.sourceConfig.selectedTables.map(table => ({
        name: table.name,
        database: table.database,
        regex: table.regex || false,
        uniqueKey: `${table.database}.${table.name}`
      }))
      sourceConfig.templateId = configData.sourceConfig.templateId
      
      // 回显目标配置
      targetConfig.dataCenter = configData.targetConfig.dataCenter
      targetConfig.instance = configData.targetConfig.instance
      targetConfig.databases = configData.targetConfig.databases
      targetConfig.selectedTables = configData.targetConfig.selectedTables.map(table => ({
        name: table.name,
        database: table.database,
        regex: table.regex || false,
        uniqueKey: `${table.database}.${table.name}`
      }))
      targetConfig.templateId = configData.targetConfig.templateId
      
      // 回显表映射关系
      tableMappings.value = configData.tableMappings.map(mapping => {
        const mappingId = Date.now().toString() + Math.random().toString(36).substr(2, 9)
        
        // 初始化字段映射分页状态
        fieldMappingCurrentPages.value.set(mappingId, 1)
        
        // 直接使用已有的字段映射，添加必要的UI状态属性
        const fieldMappings = mapping.fieldMappings.map(field => ({
          id: field.targetField || field.sourceField,
          sourceField: field.sourceField || '',
          targetField: field.targetField || '',
          mappingType: field.mappingType || 'field',
          defaultValue: field.defaultValue || '',
          sourceType: field.sourceType || '',
          targetType: field.targetType || '',
          matched: field.mappingType === 'field' && field.sourceField && field.targetField
        }))

        return {
          id: mappingId,
          sourceTable: mapping.sourceTable,
          targetTable: mapping.targetTable,
          fieldMappings
        }
      })
      
      // 清除存储的配置数据
      localStorage.removeItem('syncConfigData')
      
      // 自动展开所有映射行
      tableMappings.value.forEach(mapping => {
        expandedRows.value.add(mapping.id)
      })
      
      // 更新数据库类型
      const sourceCenter = dataCenterOptions.value.find(center => center.value === sourceConfig.dataCenter)
      const targetCenter = dataCenterOptions.value.find(center => center.value === targetConfig.dataCenter)
      if (sourceCenter) sourceConfig.dbType = sourceCenter.dbType
      if (targetCenter) targetConfig.dbType = targetCenter.dbType

      // 触发源端数据加载
      const loadSourceData = async () => {
        try {
          // 加载源端实例列表
          await fetchSourceInstances()
          // 加载源端数据库列表
          await fetchSourceDatabases()
          // 加载源端表列表
          await fetchSourceTables()
          
          // 等待DOM更新
          await nextTick()
          
          // 设置源表选中状态和正则匹配状态
          if (sourceConfig.selectedTables.length > 0) {
            // 更新表格数据中的正则匹配状态
            sourceTableList.value = sourceTableList.value.map(table => {
              const selectedTable = sourceConfig.selectedTables.find(
                selected => selected.database === table.database && selected.name === table.label
              )
              if (selectedTable) {
                return {
                  ...table,
                  regex: selectedTable.regex
                }
              }
              return table
            })
            
            // 设置选中状态
            const selectedRows = sourceTableList.value.filter(table => 
              sourceConfig.selectedTables.some(selected => 
                selected.database === table.database && 
                selected.name === table.label
              )
            )
            selectedSourceTableRows.value = selectedRows
            
            // 手动设置选中状态
            selectedRows.forEach(row => {
              sourceTableRef.value?.toggleRowSelection(row, true)
            })
          }
        } catch (error) {
          console.error('加载源端数据失败：', error)
          ElMessage.error('加载源端数据失败')
        }
      }

      // 触发目标端数据加载
      const loadTargetData = async () => {
        // 加载目标端实例列表
        await fetchTargetInstances()
        // 加载目标端数据库列表
        await fetchTargetDatabases()
        // 加载目标端表列表
        await fetchTargetTables()
        
        // 等待DOM更新
        await nextTick()
        
        // 设置目标表选中状态和正则匹配状态
        if (targetConfig.selectedTables.length > 0) {
          const selectedRows = targetTableOptions.value.filter(table => 
            targetConfig.selectedTables.some(selected => 
              selected.database === table.database && 
              selected.name === table.label
            )
          )
          selectedTargetTableRows.value = selectedRows
          
          // 手动设置选中状态和正则匹配状态
          selectedRows.forEach(row => {
            const selectedTable = targetConfig.selectedTables.find(
              selected => selected.database === row.database && selected.name === row.label
            )
            if (selectedTable) {
              row.regex = selectedTable.regex
            }
            targetTableRef.value?.toggleRowSelection(row, true)
          })
        }
      }

      // 加载表映射的字段信息
      const loadTableMappingsData = async () => {
        for (const mapping of tableMappings.value) {
          if (mapping.sourceTable && mapping.targetTable) {
            await handleTableMappingChange(mapping)
          }
        }
      }

      // 按顺序执行数据加载
      const initializeData = async () => {
        try {
          // 确保模板列表已加载
          await fetchTemplateList()
          
          // 重新设置模板ID，确保在模板列表加载后设置
          if (configData.sourceConfig.templateId) {
            sourceConfig.templateId = configData.sourceConfig.templateId
          }
          if (configData.targetConfig.templateId) {
            targetConfig.templateId = configData.targetConfig.templateId
          }
          
          // 在模板ID设置后，再次回显Kafka配置，延迟确保计算属性更新
          setTimeout(() => {
            if (configData.kafkaConfig && hasKafkaTemplate.value) {
              kafkaTopic.value = configData.kafkaConfig.kafkaTopic || ''
              kafkaPartition.value = configData.kafkaConfig.kafkaPartition || ''
              kafkaConsumerGroup.value = configData.kafkaConfig.kafkaConsumerGroup || ''
            }
          }, 2000)
          
          await loadSourceData()
          await loadTargetData()
          await loadTableMappingsData()
          ElMessage.success('配置数据加载成功')
        } catch (error) {
          console.error('加载配置数据失败：', error)
          ElMessage.error('加载配置数据失败：' + (error.message || '未知错误'))
        }
      }

      // 执行数据加载
      initializeData()
    } catch (error) {
      console.error('加载配置数据失败：', error)
      ElMessage.error('加载配置数据失败')
    }
  }
})

// 源数据源相关
const sourceDatabases = ref([])
const sourceTables = ref([])

// 目标数据源相关
const targetDatabases = ref([])
const targetTables = ref([])

// 表映射关系
const tableMappings = ref([])

// 映射类型选项
const mappingTypeOptions = [
  { label: '字段映射', value: 'field' },
  { label: '默认值', value: 'default' }
]

// 添加选中表的引用
const selectedSourceTableRows = ref([])
const selectedTargetTableRows = ref([])

// 添加展开行状态控制
const expandedRows = ref(new Set())

// 添加字段列表的响应式引用
const sourceFieldsList = ref([])
const targetFieldsList = ref([])

// 添加表格引用
const sourceTableRef = ref(null)
const targetTableRef = ref(null)

// 处理源数据中心变更
const handleSourceDataCenterChange = (value) => {
  sourceConfig.instance = ''
  sourceConfig.databases = []
  sourceConfig.selectedTables = []
  sourceFieldsCache.value.clear()
  
  // 更新数据库类型
  const selectedCenter = dataCenterOptions.value.find(center => center.value === value)
  if (selectedCenter) {
    sourceConfig.dbType = selectedCenter.dbType
  }
  
  fetchSourceInstances()
}

// 处理源实例变更
const handleSourceInstanceChange = (value) => {
  sourceConfig.databases = []
  sourceConfig.selectedTables = []
  fetchSourceDatabases()
}

// 处理源数据库变更
const handleSourceDatabaseChange = (value) => {
  // 【修复】不要清空所有选中的表，而是只清理不再存在的数据库的表
  // 当前选中的数据库列表
  const currentDatabases = value || []
  
  // 过滤掉不在当前数据库列表中的已选中表
  sourceConfig.selectedTables = sourceConfig.selectedTables.filter(selectedTable => 
    currentDatabases.includes(selectedTable.database)
  )
  
  fetchSourceTables()
}

// 处理目标数据中心变更
const handleTargetDataCenterChange = (value) => {
  targetConfig.instance = ''
  targetConfig.databases = []
  targetConfig.selectedTables = []
  targetFieldsCache.value.clear()
  
  // 更新数据库类型
  const selectedCenter = dataCenterOptions.value.find(center => center.value === value)
  if (selectedCenter) {
    targetConfig.dbType = selectedCenter.dbType
  }
  
  fetchTargetInstances()
}

// 处理目标实例变更
const handleTargetInstanceChange = (value) => {
  targetConfig.databases = []
  targetConfig.selectedTables = []
  fetchTargetDatabases()
}

// 处理目标数据库变更
const handleTargetDatabaseChange = (value) => {
  // 【修复】不要清空所有选中的表，而是只清理不再存在的数据库的表
  // 当前选中的数据库列表
  const currentDatabases = value || []
  
  // 过滤掉不在当前数据库列表中的已选中表
  targetConfig.selectedTables = targetConfig.selectedTables.filter(selectedTable => 
    currentDatabases.includes(selectedTable.database)
  )
  
  fetchTargetTables()
}

// 处理模板变更
const handleTemplateChange = () => {
  // 如果当前选择的模板不包含kafka，清空相关字段
  if (!hasKafkaTemplate.value) {
    kafkaTopic.value = ''
    kafkaPartition.value = ''
    kafkaConsumerGroup.value = ''
  }
}

// 添加恢复状态标记
const isRestoring = ref(false)

// 修改源表选择变更处理函数
const handleSourceTableSelectionChange = (selection) => {
  // 如果正在恢复选中状态，不处理选择变更
  if (isRestoring.value) {

    return
  }
  

  
  selectedSourceTableRows.value = selection
  
  // 获取当前页面显示的表
  const currentPageTables = paginatedSourceTableList.value
  
  // 获取当前页面已选中的表（直接基于用户的selection）
  const currentPageSelected = selection.map(table => ({
    name: table.label,
    database: table.database,
    regex: table.regex || false,
    uniqueKey: table.uniqueKey
  }))
  
  // 【关键修复】获取真正不在当前页面显示的已选中表
  // 这些表在其他页面，不应该受当前页面操作影响
  const otherPagesSelected = sourceConfig.selectedTables.filter(selected => 
    !currentPageTables.some(pageTable => 
      pageTable.database === selected.database && pageTable.label === selected.name
    )
  )
  

  
  // 【修复后的逻辑】直接使用当前页面选择 + 其他页面选择
  // 不需要去重，因为 otherPagesSelected 不包含当前页面的表
  const newSelectedTables = [...otherPagesSelected, ...currentPageSelected]
  
  const oldCount = sourceConfig.selectedTables.length
  sourceConfig.selectedTables = newSelectedTables
  const newCount = sourceConfig.selectedTables.length
  

}

// 修改目标表选择变更处理函数
const handleTargetTableSelectionChange = (selection) => {
  // 如果正在恢复选中状态，不处理选择变更
  if (isRestoring.value) {
  
    return
  }
  
  selectedTargetTableRows.value = selection
  
  // 获取当前页面显示的表
  const currentPageTables = paginatedTargetTableList.value
  
  // 获取当前页面已选中的表（直接基于用户的selection）
  const currentPageSelected = selection.map(table => ({
    name: table.label,
    database: table.database,
    comment: table.comment,
    uniqueKey: table.uniqueKey
  }))
  
  // 【关键修复】获取真正不在当前页面显示的已选中表
  const otherPagesSelected = targetConfig.selectedTables.filter(selected => 
    !currentPageTables.some(pageTable => 
      pageTable.database === selected.database && pageTable.label === selected.name
    )
  )
  
  // 【修复后的逻辑】直接使用当前页面选择 + 其他页面选择
  const newSelectedTables = [...otherPagesSelected, ...currentPageSelected]
  
  targetConfig.selectedTables = newSelectedTables
}

// 添加分页处理方法
const handleSourceTableSizeChange = (size) => {
  sourceTablePageSize.value = size
  sourceTableCurrentPage.value = 1
  // 分页改变后重新设置选中状态
  nextTick(() => {
    restoreSourceTableSelection()
  })
}

const handleSourceTableCurrentChange = (page) => {
  sourceTableCurrentPage.value = page
  // 分页改变后重新设置选中状态
  nextTick(() => {
    restoreSourceTableSelection()
  })
}

const handleTargetTableSizeChange = (size) => {
  targetTablePageSize.value = size
  targetTableCurrentPage.value = 1
  // 分页改变后重新设置选中状态
  nextTick(() => {
    restoreTargetTableSelection()
  })
}

const handleTargetTableCurrentChange = (page) => {
  targetTableCurrentPage.value = page
  // 分页改变后重新设置选中状态
  nextTick(() => {
    restoreTargetTableSelection()
  })
}

// 添加恢复选中状态的方法
const restoreSourceTableSelection = () => {
  if (!sourceTableRef.value) {
    return
  }
  
  if (sourceConfig.selectedTables.length === 0) {
    return
  }
  
  // 清理不存在的表，保持数据一致性
  const validSelectedTables = sourceConfig.selectedTables.filter(selected => 
    sourceTableList.value.some(table => 
      table.database === selected.database && table.label === selected.name
    )
  )
  
  if (validSelectedTables.length !== sourceConfig.selectedTables.length) {
    sourceConfig.selectedTables = validSelectedTables
  }
  
  // 设置恢复状态标记，防止触发选择变更事件
  isRestoring.value = true
  
  // 等待下一个 tick，确保 DOM 完全更新
  nextTick(() => {
    // 再次确认表格引用存在
    if (!sourceTableRef.value) {
      isRestoring.value = false
      return
    }
    
    // 清除当前选中状态
    sourceTableRef.value.clearSelection()
    console.log('🧹 清除当前选中状态')
    
    let restoredCount = 0
    // 根据当前分页数据设置选中状态
    paginatedSourceTableList.value.forEach(row => {
      const isSelected = sourceConfig.selectedTables.some(selected => 
        selected.database === row.database && 
        selected.name === row.label
      )
      if (isSelected) {
        sourceTableRef.value.toggleRowSelection(row, true)
        restoredCount++
      }
    })
    
    console.log('✅ 源表选中状态恢复完成，恢复数量:', restoredCount)
    
    // 强制更新选中行状态
    selectedSourceTableRows.value = paginatedSourceTableList.value.filter(row => 
      sourceConfig.selectedTables.some(selected => 
        selected.database === row.database && 
        selected.name === row.label
      )
    )
    
    // 延迟重置恢复状态标记
    setTimeout(() => {
      isRestoring.value = false
      console.log('🔓 释放恢复状态标记')
    }, 200)
  })
}

const restoreTargetTableSelection = () => {
  console.log('🔄 开始恢复目标表选中状态，选中表数量:', targetConfig.selectedTables.length)
  
  if (!targetTableRef.value) {
    console.log('❌ 目标表引用不存在，跳过恢复')
    return
  }
  
  if (targetConfig.selectedTables.length === 0) {
    console.log('💡 没有需要恢复的目标表选中状态')
    return
  }
  
  // 清理不存在的表，保持数据一致性
  const validSelectedTables = targetConfig.selectedTables.filter(selected => 
    targetTableOptions.value.some(table => 
      table.database === selected.database && table.label === selected.name
    )
  )
  
  if (validSelectedTables.length !== targetConfig.selectedTables.length) {
    console.log(`🧹 清理不存在的表: ${targetConfig.selectedTables.length} -> ${validSelectedTables.length}`)
    targetConfig.selectedTables = validSelectedTables
  }
  
  // 设置恢复状态标记，防止触发选择变更事件
  isRestoring.value = true
  console.log('🔒 设置恢复状态标记')
  
  // 等待下一个 tick，确保 DOM 完全更新
  nextTick(() => {
    // 再次确认表格引用存在
    if (!targetTableRef.value) {
      console.log('❌ nextTick后目标表引用不存在')
      isRestoring.value = false
      return
    }
    
    // 清除当前选中状态
    targetTableRef.value.clearSelection()
    console.log('🧹 清除当前选中状态')
    
    let restoredCount = 0
    // 根据当前分页数据设置选中状态
    paginatedTargetTableList.value.forEach(row => {
      // 【修复】正确的字段比较：selected.name 对应 row.label
      const isSelected = targetConfig.selectedTables.some(selected => 
        selected.database === row.database && 
        selected.name === row.label
      )
      if (isSelected) {
        targetTableRef.value.toggleRowSelection(row, true)
        restoredCount++
      }
    })
    
    console.log('✅ 目标表选中状态恢复完成，恢复数量:', restoredCount)
    
    // 强制更新选中行状态
    selectedTargetTableRows.value = paginatedTargetTableList.value.filter(row => 
      targetConfig.selectedTables.some(selected => 
        selected.database === row.database && 
        selected.name === row.label
      )
    )
    
    // 延迟重置恢复状态标记
    setTimeout(() => {
      isRestoring.value = false
      console.log('🔓 释放恢复状态标记')
    }, 200)
  })
}

// 修改获取源字段的方法
const getSourceFields = async (tableName) => {
  if (!sourceConfig.dataCenter || !sourceConfig.instance || !tableName) return []
  
  try {
    // 从tableName中提取数据库名和表名
    const [database, table] = tableName.split('.')
    if (!database || !table) {
      console.error('无效的表名格式:', tableName)
      return []
    }
    
    const fields = await getTableFields(
      sourceConfig.dataCenter, 
      sourceConfig.instance, 
      database,
      table
    )
    
    const formattedFields = fields.map(field => ({
      name: field.fieldName,
      type: field.fieldType,
      comment: field.comment
    }))
    
    return formattedFields
  } catch (error) {
    console.error('获取源表字段信息失败：', error)
    ElMessage.error('获取源表字段信息失败')
    return []
  }
}

const getTargetFields = async (tableName) => {
  if (!targetConfig.dataCenter || !targetConfig.instance || !tableName) return []
  
  // 从tableName中提取数据库名和表名
  const [database, table] = tableName.split('.')
  if (!database || !table) {
    console.error('无效的表名格式:', tableName)
    return []
  }
  
  // 构建缓存key
  const cacheKey = `${targetConfig.dataCenter}_${targetConfig.instance}_${database}_${table}`
  
  // 检查缓存
  if (targetFieldsCache.value.has(cacheKey)) {
    return targetFieldsCache.value.get(cacheKey)
  }
  
  try {
    const fields = await getTableFields(
      targetConfig.dataCenter, 
      targetConfig.instance, 
      database,
      table
    )
    
    const formattedFields = fields.map(field => ({
      name: field.fieldName,
      type: field.fieldType,
      comment: field.comment
    }))
    
    // 存入缓存
    targetFieldsCache.value.set(cacheKey, formattedFields)
    return formattedFields
  } catch (error) {
    console.error('获取目标表字段信息失败：', error)
    ElMessage.error('获取目标表字段信息失败')
    return []
  }
}

// 修改添加表映射的方法
const addTableMapping = () => {
  const newMapping = {
    id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
    sourceTable: '',
    targetTable: '',
    fieldMappings: []
  }
  
  // 初始化字段映射分页状态
  fieldMappingCurrentPages.value.set(newMapping.id, 1)
  
  // 使用Vue的响应式方法添加新映射
  tableMappings.value = [...tableMappings.value, newMapping]
  
  // 确保展开新添加的映射
  nextTick(() => {
    expandedRows.value.add(newMapping.id)
    
    // 自动跳转到最后一页显示新创建的映射
    const totalPages = Math.ceil(tableMappings.value.length / tableMappingPageSize.value)
    if (tableMappingCurrentPage.value < totalPages) {
      tableMappingCurrentPage.value = totalPages
    }
  })
}

// 修改映射类型变更处理函数
const handleMappingTypeChange = (row) => {
  if (row.mappingType === 'default') {
    row.sourceField = ''
    row.sourceType = ''
    row.targetField = ''
    row.targetType = ''
  } else {
  row.defaultValue = ''
  }
}

// 修改表映射变更处理函数
const handleTableMappingChange = async (mapping) => {
  // 如果已经有字段映射，则不重新获取
  if (mapping.fieldMappings && mapping.fieldMappings.length > 0) {
    return;
  }

  try {
  // 获取源表和目标表的所有字段
    const [sourceFields, targetFields] = await Promise.all([
      getSourceFields(mapping.sourceTable),
      getTargetFields(mapping.targetTable)
    ]);
    
    // 更新字段列表
    sourceFieldsList.value = sourceFields;
    targetFieldsList.value = targetFields;
  
  // 创建一个源字段的映射，用于快速查找
  const sourceFieldMap = new Map(
    sourceFields.map(field => [field.name.toLowerCase(), field])
    );
  
  // 初始化字段映射数组
    mapping.fieldMappings = [];
  
  // 遍历目标表的所有字段
  targetFields.forEach(targetField => {
      // 检查是否是特殊字段
      const isSpecialField = ['sr_createtime', 'sr_updatetime'].includes(targetField.name);
      
      // 如果是特殊字段，直接设置为默认值类型
      if (isSpecialField) {
        mapping.fieldMappings.push({
          id: targetField.name,
          sourceField: '',
          sourceType: '',
          targetField: targetField.name,
          targetType: targetField.type,
          mappingType: 'default',
          defaultValue: 'CURRENT_TIMESTAMP',
          matched: true
        });
        return;
      }
      
    // 尝试找到匹配的源字段
    let sourceField = sourceFieldMap.get(targetField.name.toLowerCase());
    // 检查是否为ProductId字段，并填充ProductId为默认值
    let productIdDefaultValue = '';
    const isProductField = ['productId', 'product_id', 'productid'].includes(targetField.name.toLowerCase());
    if (isProductField && !sourceField) {
      const sourceTable = mapping.sourceTable || '';
      const tableNameParts = sourceTable.split('.');
      const sourceDatabaseName = tableNameParts.length > 1 ? tableNameParts[0] : '';
      
      if (sourceDatabaseName) {
          for (const [languageCode, defaultValue] of PRODUCT_FIELD_MAP.entries()) {
            if (sourceDatabaseName.toLowerCase().includes(languageCode)) {
              productIdDefaultValue = defaultValue;
              break;
            }
        }
      }
    }
    
      // 添加字段映射，无论是否匹配都添加
      mapping.fieldMappings.push({
        id: targetField.name,
        sourceField: sourceField ? sourceField.name : '',
        sourceType: sourceField ? sourceField.type : '',
        targetField: targetField.name,
        targetType: targetField.type,
        mappingType: sourceField ? 'field' : 'default',
        defaultValue: sourceField ? '' : (isProductField ? productIdDefaultValue : ''), // 有源字段映射时为空，productId字段使用映射值，其他字段为空
        matched: !!sourceField
      });
    });

    // 添加未匹配的源字段
    sourceFields.forEach(sourceField => {
      // 检查源字段是否已经被映射
      const isMapped = mapping.fieldMappings.some(
        mapping => mapping.sourceField === sourceField.name
      );
      
      // 如果源字段未被映射，添加到映射列表中
      if (!isMapped) {
        mapping.fieldMappings.push({
          id: `source_${sourceField.name}`,
          sourceField: sourceField.name,
          sourceType: sourceField.type,
          targetField: '',
          targetType: '',
          mappingType: 'field',
          defaultValue: '',
          matched: false
        });
      }
    });
  } catch (error) {
    console.error('处理表映射变更失败：', error);
    ElMessage.error('处理表映射变更失败');
  }
};

// 获取状态类型
const getStatusType = (row) => {
  if (row.mappingType === 'field' && row.matched) return 'success'
  if (row.mappingType === 'field' && row.sourceField) return 'primary'
  if (row.mappingType === 'default' && row.defaultValue) return 'warning'
  return 'info'
}

// 获取状态文本
const getStatusText = (row) => {
  if (row.mappingType === 'field' && row.matched) return '自动匹配'
  if (row.mappingType === 'field' && row.sourceField) return '手动映射'
  if (row.mappingType === 'default' && row.defaultValue) return '默认值'
  return '待配置'
}

// 获取行样式
const getRowClassName = (row) => {
  if (row.mappingType === 'field' && row.matched) return 'matched-row'
  if (row.mappingType === 'field' && row.sourceField) return 'manual-row'
  if (row.mappingType === 'default' && row.defaultValue) return 'default-row'
  return 'unmatched-row'
}

// 添加展开状态变更处理函数
const handleExpandChange = (row, expanded) => {
  if (expanded) {
    expandedRows.value.add(row.id)
  } else {
    expandedRows.value.delete(row.id)
  }
}

// 修改源表选择处理函数
const handleSourceTableSelect = async (value, mapping) => {
  try {
  mapping.sourceTable = value
  if (mapping.sourceTable && mapping.targetTable) {
      // 如果是回显的映射且已有字段映射，不重新获取
      if (mapping.fieldMappings && mapping.fieldMappings.length > 0) {
        // 确保字段信息已加载到缓存中
        await ensureFieldsLoaded(mapping)
      } else {
        await handleTableMappingChange(mapping)
      }
  }
  // 保持展开状态
  expandedRows.value.add(mapping.id)
  } catch (error) {
    console.error('处理源表选择失败：', error)
    ElMessage.error('处理源表选择失败')
  }
}

const handleTargetTableSelect = async (value, mapping) => {
  try {
  mapping.targetTable = value
  if (mapping.sourceTable && mapping.targetTable) {
      // 如果是回显的映射且已有字段映射，不重新获取
      if (mapping.fieldMappings && mapping.fieldMappings.length > 0) {
        // 确保字段信息已加载到缓存中
        await ensureFieldsLoaded(mapping)
      } else {
        await handleTableMappingChange(mapping)
      }
  }
  // 保持展开状态
  expandedRows.value.add(mapping.id)
  } catch (error) {
    console.error('处理目标表选择失败：', error)
    ElMessage.error('处理目标表选择失败')
  }
}

// 修改删除表映射的方法
const removeTableMapping = (index) => {
  try {
    // 获取当前页的映射
    const currentPageMappings = paginatedTableMappings.value
    const mappingToRemove = currentPageMappings[index]
    
    if (!mappingToRemove) {
      console.error('未找到要删除的映射')
      return
    }
    
    // 清理字段映射分页状态
    fieldMappingCurrentPages.value.delete(mappingToRemove.id)
    
    // 从展开行集合中移除
    expandedRows.value.delete(mappingToRemove.id)
    
    // 从原始数组中删除
    const originalIndex = tableMappings.value.findIndex(m => m.id === mappingToRemove.id)
    if (originalIndex !== -1) {
      tableMappings.value.splice(originalIndex, 1)
    }
    
    // 如果删除后当前页没有数据，且不是第一页，则跳转到上一页
    nextTick(() => {
      if (paginatedTableMappings.value.length === 0 && tableMappingCurrentPage.value > 1) {
        tableMappingCurrentPage.value--
      }
    })
  } catch (error) {
    console.error('删除表映射失败：', error)
    ElMessage.error('删除表映射失败')
  }
}

// 修改删除字段映射的方法，支持分页
const removeFieldMapping = (mapping, fieldItem) => {
  // 根据字段的唯一标识删除，而不是依赖索引
  const index = mapping.fieldMappings.findIndex(field => 
    field.id === fieldItem.id || 
    (field.targetField === fieldItem.targetField && field.sourceField === fieldItem.sourceField)
  )
  
  if (index !== -1) {
    mapping.fieldMappings.splice(index, 1)
    
    // 如果删除后当前页没有数据，且不是第一页，则跳转到上一页
    const mappingData = getFieldMappingData(mapping)
    if (mappingData.needPagination && mappingData.data.length === 0) {
      const currentPage = fieldMappingCurrentPages.value.get(mapping.id) || 1
      if (currentPage > 1) {
        fieldMappingCurrentPages.value.set(mapping.id, currentPage - 1)
      }
    }
  }
}

// 修改步骤控制的验证逻辑
const nextStep = () => {
  console.log('🔢 nextStep 函数被调用，当前步骤:', currentStep.value)
  
  if (currentStep.value < 2) {
    if (currentStep.value === 0 && (!sourceConfig.selectedTables.length || !targetConfig.selectedTables.length)) {
      ElMessage.warning('请至少选择一个源表和目标表')
      console.log('❌ 验证失败：缺少源表或目标表')
      return
    }
    if (currentStep.value === 1 && !tableMappings.value.length) {
      ElMessage.warning('请至少配置一个表映射关系')
      console.log('❌ 验证失败：缺少表映射关系')
      return
    }
    
    // 在进入配置映射关系步骤时，过滤表映射
    if (currentStep.value === 0) {
      // 过滤表映射，只保留源表和目标表都在选中列表中的映射
      tableMappings.value = tableMappings.value.filter(mapping => {
        // 检查源表是否在选中的表中
        const sourceTableSelected = sourceConfig.selectedTables.some(table => 
          `${table.database}.${table.name}` === mapping.sourceTable
        )
        // 检查目标表是否在选中的表中
        const targetTableSelected = targetConfig.selectedTables.some(table => 
          `${table.database}.${table.name}` === mapping.targetTable
        )
        // 只保留源表和目标表都在选中列表中的映射
        return sourceTableSelected && targetTableSelected
      })
    }
    
    const oldStep = currentStep.value
    currentStep.value++
    console.log(`✅ 步骤更新: ${oldStep} -> ${currentStep.value}`)
    
    // 强制触发DOM更新
    nextTick(() => {
      console.log('🎯 DOM更新后，当前步骤:', currentStep.value)
    })
  } else {
    console.log('⚠️ 已经是最后一步，无法继续')
  }
}

const prevStep = () => {
  console.log('⬅️ prevStep 函数被调用，当前步骤:', currentStep.value)
  
  if (currentStep.value > 0) {
    const oldStep = currentStep.value
    currentStep.value--
    // 强制触发DOM更新并恢复表格选中状态
    nextTick(() => {
      // 如果回退到第一步（选择数据源），需要恢复表格选中状态
      if (currentStep.value === 0) {
        // 延迟恢复，确保DOM完全渲染
        setTimeout(() => {
          if (sourceConfig.selectedTables.length > 0) {
            console.log('📋 恢复源表选中状态，选中表数量:', sourceConfig.selectedTables.length)
            restoreSourceTableSelection()
          }
          
          if (targetConfig.selectedTables.length > 0) {
            console.log('📋 恢复目标表选中状态，选中表数量:', targetConfig.selectedTables.length)
            restoreTargetTableSelection()
          }
        }, 100)
      }
    })
  } else {
    console.log('⚠️ 已经是第一步，无法返回')
  }
}

// 修改提交配置的方法
const submitConfig = async () => {
  try {
    loading.value = true
    
    // 验证模板绑定
    if (!sourceConfig.templateId) {
      ElMessage.warning('请为源数据库选择绑定模板')
      return
    }
    if (!targetConfig.templateId) {
      ElMessage.warning('请为目标数据库选择绑定模板')
      return
    }
    
    // 验证分组不重名，编辑类不验证
    if (!configId.value) {
      if (kafkaTopic.value) {
        const topicName = kafkaTopic.value
        const consumerGroup = kafkaConsumerGroup.value
        // 发起请求验证，返回 true 则不重名，返回 false 则重名
        const isUnique = await validateKafkaConsumerGroup(topicName, consumerGroup)
        if (!isUnique) {
          ElMessage.warning('存在相同的主题及消费组，请更换主题或消费组名称')
          return
        }
      }
  
      // 验证分区数是否为有效数字
      if (kafkaPartition.value) {
        const partitionNum = parseInt(kafkaPartition.value)
        if (isNaN(partitionNum) || partitionNum <= 0) {
          ElMessage.warning('分区数必须是大于0的整数')
          return
        }
      }
    }
    
    // 构建配置数据
    const sourceCenter = dataCenterOptions.value.find(center => center.value === sourceConfig.dataCenter)
    const targetCenter = dataCenterOptions.value.find(center => center.value === targetConfig.dataCenter)

    if (!sourceCenter || !targetCenter) {
      ElMessage.error('请选择源端和目标端数据中心')
      return
    }

    const configData = {
      sourceConfig: {
        dataCenter: sourceConfig.dataCenter,
        instance: sourceConfig.instance,
        dbType: sourceCenter.dbType,
        databases: sourceConfig.databases,
        templateId: sourceConfig.templateId,
        selectedTables: sourceConfig.selectedTables.map(table => ({
        name: table.name,
          database: table.database,
          regex: table.regex || false
        }))
      },
      targetConfig: {
        dataCenter: targetConfig.dataCenter,
        instance: targetConfig.instance,
        dbType: targetCenter.dbType,
        databases: targetConfig.databases,
        templateId: targetConfig.templateId,
        selectedTables: targetConfig.selectedTables.map(table => ({
          name: table.name,
          database: table.database,
          regex: table.regex || false
        }))
      },
      // 添加Kafka相关配置
      kafkaConfig: hasKafkaTemplate.value ? {
        kafkaTopic: kafkaTopic.value,
        kafkaPartition: kafkaPartition.value,
        kafkaConsumerGroup: kafkaConsumerGroup.value
      } : null,
      tableMappings: tableMappings.value.map(mapping => { 
        return {
          sourceTable: `${mapping.sourceTable}`,
          targetTable: `${mapping.targetTable}`,
          fieldMappings: mapping.fieldMappings.map(field => ({
            sourceField: field.sourceField,
            targetField: field.targetField,
            mappingType: field.mappingType,
            defaultValue: field.mappingType === 'default' ? field.defaultValue : '',
            sourceType: field.sourceType,
            targetType: field.targetType
          }))
        }
      })
    }

    let response
    if (configId.value) {
      response = await generateSyncConfig(configData, configId.value)
      ElMessage.success('配置更新成功')
    } else {
      response = await generateSyncConfig(configData)
      ElMessage.success('配置生成成功')
    }
    
    // 跳转到任务列表页面
    router.push('/tasks')
    
  } catch (error) {
    console.error('生成配置失败：', error)
    ElMessage.error('生成配置失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 修改源字段变更处理函数
const handleSourceFieldChange = (row) => {
  // 当选择源字段时，更新源字段类型
  const selectedField = sourceFieldsList.value.find(f => f.name === row.sourceField)
  if (selectedField) {
    row.sourceType = selectedField.type
  }
}

// 修改目标字段变更处理函数
const handleTargetFieldChange = (row, mapping) => {
  // 当选择目标字段时，更新目标字段类型
  const selectedField = targetFieldsList.value.find(f => f.name === row.targetField)
  if (selectedField) {
    row.targetType = selectedField.type
    // 如果目标字段是sr_createtime或sr_updatetime，自动设置为默认值类型并填充CURRENT_TIMESTAMP
    if (['sr_createtime', 'sr_updatetime'].includes(row.targetField)) {
      row.mappingType = 'default'
      row.defaultValue = 'CURRENT_TIMESTAMP'
      row.sourceField = ''
      row.sourceType = ''
    }
  }
}

// 获取源表完整名称
const getSourceTableFullName = (tableName) => {
  const tableInfo = sourceConfig.selectedTables.find(t => t.name === tableName)
  return tableInfo ? `${tableInfo.database}.${tableName}` : tableName
}

// 获取目标表完整名称
const getTargetTableFullName = (tableName) => {
  const tableInfo = targetConfig.selectedTables.find(t => t.name === tableName)
  return tableInfo ? `${tableInfo.database}.${tableName}` : tableName
}

// 添加新增字段映射的方法
const addFieldMapping = async (mapping) => {
  try {
    // 设置加载状态
    loadingFieldsMap.value.set(mapping.id, true)
    
    // 确保有源表和目标表的字段信息
    await ensureFieldsLoaded(mapping)
    
    const newFieldMapping = {
      id: Date.now().toString(),
      sourceField: '',
      targetField: '',
      mappingType: 'field',
      defaultValue: '',
      sourceType: '',
      targetType: '',
      matched: false
    }
    mapping.fieldMappings.push(newFieldMapping)
  } catch (error) {
    console.error('添加字段映射失败：', error)
    ElMessage.error('添加字段映射失败')
  } finally {
    loadingFieldsMap.value.set(mapping.id, false)
  }
}

// 确保字段信息已加载
const ensureFieldsLoaded = async (mapping) => {
  if (!mapping.sourceTable || !mapping.targetTable) {
    throw new Error('请先选择源表和目标表')
  }
  
  // 检查是否已有该表的字段信息
  const sourceKey = mapping.sourceTable
  const targetKey = mapping.targetTable
  
  if (!tableLevelSourceFields.value.has(sourceKey) || !tableLevelTargetFields.value.has(targetKey)) {
    // 获取字段信息
    const [sourceFields, targetFields] = await Promise.all([
      getSourceFields(mapping.sourceTable),
      getTargetFields(mapping.targetTable)
    ])
    
    // 缓存字段信息
    tableLevelSourceFields.value.set(sourceKey, sourceFields)
    tableLevelTargetFields.value.set(targetKey, targetFields)
    
    // 更新全局字段列表
    sourceFieldsList.value = sourceFields
    targetFieldsList.value = targetFields
  } else {
    // 使用缓存的字段信息
    sourceFieldsList.value = tableLevelSourceFields.value.get(sourceKey)
    targetFieldsList.value = tableLevelTargetFields.value.get(targetKey)
  }
}

// 修改获取源字段映射的方法
const getSourceFieldsForMapping = (mapping) => {
  const sourceKey = mapping.sourceTable
  const cachedFields = tableLevelSourceFields.value.get(sourceKey)
  return cachedFields || sourceFieldsList.value || []
}

// 修改获取目标字段映射的方法
const getTargetFieldsForMapping = (mapping) => {
  const targetKey = mapping.targetTable
  const cachedFields = tableLevelTargetFields.value.get(targetKey)
  return cachedFields || targetFieldsList.value || []
}

// 修改正则匹配变更处理函数
const handleRegexChange = (row) => {
  // 更新选中表中的正则匹配标志
  const selectedTable = sourceConfig.selectedTables.find(
    table => table.database === row.database && table.name === row.label
  )
  if (selectedTable) {
    selectedTable.regex = row.regex
  }
}

// 处理表映射分页变更
const handleTableMappingSizeChange = (size) => {
  tableMappingPageSize.value = size
  tableMappingCurrentPage.value = 1
}

const handleTableMappingCurrentChange = (page) => {
  tableMappingCurrentPage.value = page
}

// 展开全部映射
const expandAllMappings = () => {
  paginatedTableMappings.value.forEach(mapping => {
    expandedRows.value.add(mapping.id)
  })
  ElMessage.success('已展开当前页所有表映射')
}

// 收起全部映射
const collapseAllMappings = () => {
  paginatedTableMappings.value.forEach(mapping => {
    expandedRows.value.delete(mapping.id)
  })
  ElMessage.success('已收起当前页所有表映射')
}

// 智能映射
const smartMapping = () => {
  if (!sourceConfig.selectedTables.length || !targetConfig.selectedTables.length) {
    ElMessage.warning('请先选择源表和目标表')
    return
  }

  let matchedCount = 0
  let skippedCount = 0
  const unmatchedSourceTables = []

  // 获取已经存在映射的源表
  const existingSourceTables = new Set(
    tableMappings.value
      .filter(mapping => mapping.sourceTable)
      .map(mapping => mapping.sourceTable)
  )

  // 获取已经存在映射的目标表
  const existingTargetTables = new Set(
    tableMappings.value
      .filter(mapping => mapping.targetTable)
      .map(mapping => mapping.targetTable)
  )
  
  console.log('🔍 智能映射开始，现有映射数量:', tableMappings.value.length)

  // 为每个源表寻找匹配的目标表（只处理未映射的源表）
  sourceConfig.selectedTables.forEach(sourceTable => {
    const sourceTableFullName = `${sourceTable.database}.${sourceTable.name}`
    
    // 检查该源表是否已经有映射
    if (existingSourceTables.has(sourceTableFullName)) {
      skippedCount++
      return
    }
    
    const sourceTableName = sourceTable.name.toLowerCase()
    
    // 寻找匹配的目标表（排除已经被映射的目标表）
    const matchedTargetTable = targetConfig.selectedTables.find(targetTable => {
      const targetTableFullName = `${targetTable.database}.${targetTable.name}`
      
      // 如果目标表已经被映射，跳过
      if (existingTargetTables.has(targetTableFullName)) {
        return false
      }
      
      const targetTableName = targetTable.name.toLowerCase()
      
      // 匹配规则：目标表名等于或包含源表名
      return targetTableName === sourceTableName || 
             targetTableName.includes(sourceTableName) ||
             sourceTableName.includes(targetTableName)
    })

    if (matchedTargetTable) {
      // 创建表映射
      const mappingId = Date.now().toString() + Math.random().toString(36).substr(2, 9)
      
      // 初始化字段映射分页状态
      fieldMappingCurrentPages.value.set(mappingId, 1)
      
      const newMapping = {
        id: mappingId,
        sourceTable: sourceTableFullName,
        targetTable: `${matchedTargetTable.database}.${matchedTargetTable.name}`,
        fieldMappings: []
      }

      tableMappings.value.push(newMapping)
      expandedRows.value.add(mappingId)
      matchedCount++
      
      // 将新映射的目标表添加到已映射集合中，避免重复映射
      existingTargetTables.add(`${matchedTargetTable.database}.${matchedTargetTable.name}`)

      // 异步处理字段映射
      nextTick(async () => {
        try {
          await handleTableMappingChange(newMapping)
        } catch (error) {
          console.error('处理字段映射失败：', error)
        }
      })
    } else {
      unmatchedSourceTables.push(sourceTable.name)
    }
  })

  // 显示匹配结果
  const resultMessages = []
  
  if (matchedCount > 0) {
    resultMessages.push(`新增 ${matchedCount} 个表映射关系`)
  }
  
  if (skippedCount > 0) {
    resultMessages.push(`保留 ${skippedCount} 个已有映射`)
  }
  
  if (resultMessages.length > 0) {
    ElMessage.success(`智能映射完成！${resultMessages.join('，')}`)
  }
  
  if (unmatchedSourceTables.length > 0) {
    ElMessage.warning(`以下源表未找到匹配的目标表：${unmatchedSourceTables.join('、')}`)
  }

  if (matchedCount === 0 && skippedCount === 0) {
    ElMessage.warning('未找到任何匹配的表映射关系')
  }
  
  console.log('📈 智能映射完成: 新增', matchedCount, '个，保留', skippedCount, '个，总计', tableMappings.value.length, '个映射')
}

// 监听筛选条件变化，重置分页
watch(tableMappingFilter, () => {
  tableMappingCurrentPage.value = 1
})

// 监听步骤变化，确保在回退到第一步时恢复表格选中状态
watch(currentStep, (newStep, oldStep) => {
  console.log('👀 步骤变化监听器:', oldStep, '->', newStep)
  
  // 当从其他步骤回到第一步时，恢复表格选中状态
  if (newStep === 0 && oldStep > 0) {
    console.log('🔄 监听到回退到数据源选择步骤')
    
    // 等待DOM更新完成
    nextTick(() => {
      // 再次延迟，确保表格组件完全渲染
      setTimeout(() => {
        if (sourceConfig.selectedTables.length > 0) {
          console.log('📋 通过watch恢复源表选中状态')
          restoreSourceTableSelection()
        }
        
        if (targetConfig.selectedTables.length > 0) {
          console.log('📋 通过watch恢复目标表选中状态')
          restoreTargetTableSelection()
        }
      }, 150)
    })
  }
})

// 监听源表和目标表筛选条件变化，重置分页并恢复选中状态
watch(sourceTableFilter, () => {
  sourceTableCurrentPage.value = 1
  nextTick(() => {
    restoreSourceTableSelection()
  })
})

watch(targetTableFilter, () => {
  targetTableCurrentPage.value = 1
  nextTick(() => {
    restoreTargetTableSelection()
  })
})





// 计算选中数量的计算属性（只计算实际存在的表）
const selectedSourceTableCount = computed(() => {
  if (!sourceTableList.value.length) return 0
  
  // 只计算在当前库表列表中实际存在的选中表
  return sourceConfig.selectedTables.filter(selected => 
    sourceTableList.value.some(table => 
      table.database === selected.database && table.label === selected.name
    )
  ).length
})

const selectedTargetTableCount = computed(() => {
  if (!targetTableOptions.value.length) return 0
  
  // 只计算在当前库表列表中实际存在的选中表
  return targetConfig.selectedTables.filter(selected => 
    targetTableOptions.value.some(table => 
      table.database === selected.database && table.label === selected.name
    )
  ).length
})

// 计算在当前筛选结果中的选中数量（用于显示筛选状态下的统计）
const selectedSourceTableCountInFilter = computed(() => {
  const filteredTables = filteredSourceTableList.value
  return filteredTables.filter(table => 
    sourceConfig.selectedTables.some(selected => 
      selected.database === table.database && selected.name === table.label
    )
  ).length
})

const selectedTargetTableCountInFilter = computed(() => {
  const filteredTables = filteredTargetTableList.value
  return filteredTables.filter(table => 
    targetConfig.selectedTables.some(selected => 
      selected.database === table.database && selected.name === table.label
    )
  ).length
})

// 字段映射分页管理（仅当字段数量>100时启用）
const fieldMappingPageSize = ref(50) // 每页显示50个字段
const fieldMappingCurrentPages = ref(new Map()) // 每个表映射的当前页

// 获取字段映射分页数据
const getFieldMappingData = (mapping) => {
  if (!mapping.fieldMappings || mapping.fieldMappings.length <= 100) {
    // 字段数量≤100时，直接返回所有字段
    return {
      data: mapping.fieldMappings || [],
      total: mapping.fieldMappings?.length || 0,
      needPagination: false,
      currentPage: 1,
      totalPages: 1
    }
  }
  
  // 字段数量>100时，启用分页
  const currentPage = fieldMappingCurrentPages.value.get(mapping.id) || 1
  const total = mapping.fieldMappings.length
  const totalPages = Math.ceil(total / fieldMappingPageSize.value)
  const startIndex = (currentPage - 1) * fieldMappingPageSize.value
  const endIndex = startIndex + fieldMappingPageSize.value
  
  return {
    data: mapping.fieldMappings.slice(startIndex, endIndex),
    total,
    needPagination: true,
    currentPage,
    totalPages
  }
}

// 字段映射分页处理
const handleFieldMappingPageChange = (mapping, page) => {
  fieldMappingCurrentPages.value.set(mapping.id, page)
}

// 计算未配置的字段数量
const getUnmappedFieldsCount = (mapping) => {
  if (!mapping.fieldMappings || mapping.fieldMappings.length === 0) {
    return 0
  }
  
  return mapping.fieldMappings.filter(field => {
    // 检查字段是否未配置：
    // 1. 映射类型为字段映射但没有选择源字段，且目标字段也没有选择
    // 2. 映射类型为默认值但没有填写默认值
    if (field.mappingType === 'field') {
      // 字段映射类型：必须有源字段和目标字段
      return !field.sourceField || !field.targetField
    } else if (field.mappingType === 'default') {
      // 默认值类型：必须有默认值和目标字段
      return !field.defaultValue || !field.targetField
    }
    return true // 其他情况视为未配置
  }).length
}
</script>

<style scoped>
.wizard-container {
  max-width: 1600px;  /* 从1200px增加到1600px */
  margin: 0 auto;
  padding: 20px;
}

.step-content {
  margin-top: 40px;
}

.database-selection {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f7fa;
  padding: 12px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.step-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

/* 映射配置页面样式 */
.field-mapping-container {
  padding: 20px 40px;  /* 增加左右内边距，减少上下内边距 */
  background-color: #f8f9fa;
  border-radius: 4px;
}

.field-mapping-table {
  width: 100% !important;
  margin: 0 auto;
}

.mapping-title {
  font-size: 15px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 20px;
  text-align: center;
}

.field-count-info {
  font-size: 13px;
  font-weight: 400;
  color: #909399;
  margin-left: 8px;
}

.error-info {
  font-size: 13px;
  font-weight: 500;
  color: #f56c6c;
  margin-left: 8px;
}

/* 字段映射分页样式 */
.field-mapping-pagination {
  margin: 16px 0;
  display: flex;
  justify-content: center;
  padding: 8px 0;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
}

.field-mapping-pagination :deep(.el-pagination) {
  padding: 0;
}

.field-mapping-pagination :deep(.el-pagination .el-pagination__total) {
  margin-right: auto;
  color: #606266;
  font-size: 12px;
}

.field-mapping-pagination :deep(.el-pagination .el-pager .number) {
  min-width: 24px;
  height: 24px;
  line-height: 24px;
  font-size: 12px;
}

.field-mapping-pagination :deep(.el-pagination .el-pagination__prev),
.field-mapping-pagination :deep(.el-pagination .el-pagination__next) {
  padding: 0 6px;
  font-size: 12px;
}

.field-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.field-type {
  color: #909399;
  font-size: 13px;
}

.field-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  height: 50px;
}

:deep(.el-table__row) {
  height: 50px;
}

/* 映射状态样式 */
:deep(.matched-row) {
  background-color: #f0f9eb;
}

:deep(.manual-row) {
  background-color: #ecf5ff;
}

:deep(.default-row) {
  background-color: #fdf6ec;
}

:deep(.unmatched-row) {
  background-color: #fff7ed;
}

/* 表单控件样式 */
.el-select {
  width: 100%;
}

.el-input {
  width: 100%;
}

/* 卡片样式优化 */
.source-db, .target-db {
  height: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-card__header) {
  padding: 0;
}

/* 展开行样式 */
:deep(.el-table__expand-icon) {
  margin-right: 10px;
}

/* 添加映射按钮样式 */
.table-mapping-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.table-mapping-actions .el-button {
  padding: 12px 25px;
  font-size: 14px;
}

/* 字段映射操作按钮样式 */
.field-mapping-actions {
  margin-top: 15px;
  display: flex;
  justify-content: center;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
}

.field-mapping-actions .el-button {
  padding: 8px 16px;
  font-size: 13px;
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 12px;
  padding: 0 12px;
  height: 24px;
  line-height: 24px;
}

/* 表格内选择器样式 */
:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

/* Steps 组件样式优化 */
:deep(.el-steps) {
  padding: 20px 0;
}

:deep(.el-step__title) {
  font-size: 15px;
  font-weight: 500;
}

:deep(.el-step__head.is-success) {
  color: #67c23a;
  border-color: #67c23a;
}

/* 确认页面样式 */
.mapping-summary-title {
  margin: 20px 0;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  text-align: center;
}

/* 添加加载状态样式 */
:deep(.el-button.is-loading) {
  position: relative;
  pointer-events: none;
}

:deep(.el-button.is-loading:before) {
  pointer-events: none;
  content: '';
  position: absolute;
  left: -1px;
  top: -1px;
  right: -1px;
  bottom: -1px;
  border-radius: inherit;
  background-color: rgba(255, 255, 255, 0.35);
}

/* 添加数据库类型和模板选择器的样式 */
.db-type-with-template {
  display: flex;
  align-items: center;
}

.db-type-with-template span {
  font-weight: 500;
  color: #606266;
  margin-right: 10px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

/* 修改筛选框样式 */
.table-filter {
  margin-bottom: 16px;
}

.table-filter .el-input {
  width: 100%;
}

.table-filter .el-input__wrapper {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.table-filter .el-input__wrapper:hover {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.table-filter .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

/* 添加已选择表数量提示样式 */
.selected-count {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: #409EFF;
  font-weight: 500;
}

/* 添加分页样式 */
.table-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-pagination) {
  padding: 0;
}

:deep(.el-pagination .el-pagination__total) {
  margin-right: auto;
  color: #606266;
  font-size: 13px;
}

:deep(.el-pagination .el-pagination__sizes) {
  margin-right: 10px;
}

:deep(.el-pagination .el-pagination__jump) {
  margin-left: 10px;
}

:deep(.el-pagination .el-select .el-input) {
  height: 28px;
}

:deep(.el-pagination .el-input__inner) {
  height: 28px;
  line-height: 28px;
  border-radius: 4px;
}

/* 表映射搜索和过滤 */
.table-mapping-filters {
  margin-bottom: 20px;
}

.table-mapping-filters .el-row {
  display: flex;
  align-items: center;
}

.table-mapping-filters .el-input {
  width: 100%;
}

.table-mapping-filters .el-select {
  width: 100%;
}

.filter-actions {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.filter-actions .el-button {
  margin-right: 10px;
}

.mapping-count {
  margin-left: 10px;
  font-size: 14px;
  color: #606266;
}

/* 表映射分页控制 */
.table-mapping-pagination-top {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  padding: 8px 0;
  border: 1px solid #ebeef5;
  background-color: #fafafa;
  border-radius: 4px;
}

.table-mapping-pagination-top :deep(.el-pagination) {
  padding: 0;
}

.table-mapping-pagination-top :deep(.el-pagination .el-pagination__total) {
  margin-right: auto;
  color: #606266;
  font-size: 13px;
}

.table-mapping-pagination-top :deep(.el-pagination .el-pager .number) {
  min-width: 28px;
  height: 28px;
  line-height: 28px;
  font-size: 13px;
}

.table-mapping-pagination-top :deep(.el-pagination .el-pagination__prev),
.table-mapping-pagination-top :deep(.el-pagination .el-pagination__next) {
  padding: 0 8px;
  font-size: 13px;
}
</style> 